<!--
    报价明细
 -->
<template>
  <div >
    <a-row class="smart-table-btn-block operate-header" >
      <a-col :flex="5">
        <div class="smart-table-operate-block">
          <a-button  type="primary" @click="addItem(1)">
            <template #icon>
              <PlusOutlined />
            </template>
            添加主材
          </a-button>
          <a-button  type="primary" @click="addItem(3)">
            <template #icon>
              <PlusOutlined />
            </template>
            添加配件
          </a-button>
          <a-button  type="primary" @click="showCalculate">
            <template #icon><CalculatorOutlined /></template>
            计算米重
          </a-button>
          <a-button  type="primary" danger :disabled="selectedRowKeyList.length === 0" @click="onDelete">
            <template #icon>
              <DeleteOutlined />
            </template>
            批量删除
          </a-button>

          <span v-if="templateList.length > 0">选择模板：</span>
          <a-select v-if="templateList.length > 0"
              v-model:value="templateId"
              style="width: 240px"
              placeholder="选择模板"
              :showSearch="true"
              :allowClear="true"
              :size="size"
              @change="onTemplateChange"
          >
            <a-select-option v-for="item in templateList" :key="item.templateId" :value="item.templateId">
              {{ item.templateName }}
            </a-select-option>
          </a-select>
        </div>
      </a-col>

      <a-col :flex="1">
        <div :style="{position: 'absolute',right: 0,textAlign: 'right'}" >
          <!--          <a-button style="margin-right: 8px" @click="onClose">关闭</a-button>-->
          <a-button type="primary" @click="onSubmit">提交</a-button>
        </div>
      </a-col>
    </a-row>
    <a-card >
      <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }" >
        <a-row :gutter="30">
          <a-col :span="12">
            <a-form-item label="报价单名称"  name="quotationName">
              <a-input style="width: 100%" v-model:value="form.quotationName" placeholder="报价单名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="备注" name="remark">
              <a-input style="width: 100%" v-model:value="form.remark" placeholder="备注"/>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="30">
          <a-col :span="12">
            <a-form-item label="长"  name="quotationLong">
              <a-input-number style="width: 100%" v-model:value="form.quotationLong" placeholder="长"
                              @change="value => calculateMoney(value, 0)"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="高度"  name="quotationHeight">
              <a-input-number style="width: 100%" v-model:value="form.quotationHeight" placeholder="高度"
                              @change="value => calculateMoney(value, 0)"/>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="30">
          <a-col :span="12">
            <a-form-item label="计价方式"  name="pricingType" @change="handlePricingChange">
              <a-radio-group v-model:value="form.pricingType">
                <a-radio :value="0">长度</a-radio>
                <a-radio :value="3">面积</a-radio>
                <a-radio :value="1">个</a-radio>
                <a-radio :value="2">套</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="图纸"  name="drawingPath">
              <FileUpload
                  :defaultFileList="form.drawingPath"
                  :folder="FILE_FOLDER_TYPE_ENUM.COMMON.value"
                  buttonText="上传 文件"
                  listType="text"
                  @change="e => form.drawingPath = e"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-table
            size="small"
            :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange, getCheckboxProps: getCheckboxProps }"
            :dataSource="form.list"
            :columns="columns"
            :rowKey="(record,index)=>{return index}"
            :bordered="true"
            :loading="tableLoading"
            :pagination="false"
        >
          <!--
                    :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
          -->
          <template #bodyCell="{ text, record, index, column }">
            <!--          品名-->
            <template v-if="column.dataIndex === 'productName'">
              <a-form-item :name="column.dataIndex" class="form-item-no-margin">
                <a-input style="width: 100%" v-model:value="record.productName" :placeholder="column.title"
                         :disabled="record.type !== 1 && record.type !== 3"/>
              </a-form-item>
            </template>
            <!--          规格-->
            <template v-if="column.dataIndex === 'specifications'">
              <a-form-item :name="column.dataIndex"  class="form-item-no-margin">
                <a-input style="width: 100%" v-model:value="record.specifications" :placeholder="column.title"
                         :disabled="record.type !== 1 && record.type !== 3"/>
              </a-form-item>
            </template>
            <!--          比重-->
            <template v-if="column.dataIndex === 'specificWeight'">
              <a-form-item  :name="column.dataIndex" class="form-item-no-margin">
                <a-input-number style="width: 100%" v-model:value="record.specificWeight" :placeholder="column.title"
                                :disabled="record.type !== 1" min="0" :precision="2" @change="value => handleInputChange(value, index)"/>
              </a-form-item>
            </template>
            <!--          用量-->
            <template v-if="column.dataIndex === 'usagee'">
              <a-form-item :name="column.dataIndex" class="form-item-no-margin">
                <a-input-number style="width: 100%" v-model:value="record.usagee" :placeholder="column.title"
                                min="0" :precision="2" @change="value => handleInputChange(value, index)"
                                :disabled="record.type !== 1 && record.type !== 3"/>
              </a-form-item>
            </template>
            <!--          单价-->
            <template v-if="column.dataIndex === 'unitPrice'">
              <a-form-item :name="column.dataIndex" class="form-item-no-margin">
                <a-input-number style="width: 100%" v-model:value="record.unitPrice" :placeholder="column.title"
                                min="0" :precision="2" @change="value => handleInputChange(value, index)"
                                :formatter="value => inputFormatter(value, record)"
                                :disabled="record.type !== 1 && record.type !== 2 && record.type !== 3 && record.type !== 11 && record.type !== 13"/>
              </a-form-item>
            </template>
            <!--          金额-->
            <template v-if="column.dataIndex === 'sumOfMoney'">
              <!--        :rules="[{ required: true,  message: '请输入金额'}]"-->
              <a-form-item :name="column.dataIndex" class="form-item-no-margin">
                <a-input-number style="width: 100%" v-model:value="record.sumOfMoney" :placeholder="column.title"
                                min="0" :precision="2"  @change="value => calculateMoney(value, index)"/>
              </a-form-item>
            </template>
            <!--          备注-->
            <template v-if="column.dataIndex === 'remark'">
              <a-form-item :name="column.dataIndex" class="form-item-no-margin">
                <a-input style="width: 100%" v-model:value="record.remark" :placeholder="column.title" />
              </a-form-item>
            </template>
          </template>
        </a-table>
      </a-form>

    </a-card>


    <FuncExpressionCalculate  ref="calculateRef"/>
  </div>

</template>

<script setup>
  import {reactive, ref, onMounted, watch} from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { SmartLoading } from '/src/components/framework/smart-loading';
  import { quotationApi } from '/src/api/business/project/quotation-api';
  import { smartSentry } from '/src/lib/smart-sentry';
  import {useRoute} from "vue-router";
  import FuncExpressionCalculate from "/@/views/business/erp/expression/func-expression-calculate.vue";
  import { quotationTemplateApi } from '/@/api/business/template/quotation-template-api';
  import {FILE_FOLDER_TYPE_ENUM} from "/@/constants/support/file-const.js";
  import FileUpload from "/@/components/support/file-upload/index.vue";

  const route = useRoute();

  const editFlag = ref(false);

  let projectId = ref();
  let quotationId = ref();
  onMounted(() => {
    if (route.query.projectId) {
      projectId.value = Number(route.query.projectId);
    }
    if (route.query.quotationId) {
      quotationId.value = Number(route.query.quotationId);
      getDetail();
    }
  });

  function inputFormatter(value, record) {
    if(record.type === 2 || record.type === 11 || record.type === 13) {
      if (value) {
        return `${value}%`
      } else  {
        return `${value}`
      }
    } else {
      return `${value}`
    }
  }

  // 详情
  let detail = ref({});

  async function getDetail() {
    try {
      if (quotationId.value === -1) {
        await queryTemplateList()
      }
      let result = await quotationApi.detail(quotationId.value);
      detail.value = result.data;
      form.value = result.data;
    } catch (error) {
      smartSentry.captureError(error);
    } finally {
      SmartLoading.hide();
    }
  }

  // 组件ref
  const formRef = ref();
  let form = ref({})
  const rules = {
    quotationName: [{ required: true, message: '报价名称 必填' }],
    quotationLong: [{ required: true, message: '报价长度 必填' }],
    quotationHeight: [{ required: true, message: '报价高度 必填' }],
    pricingType: [{ required: true, message: '报价方式 必填' }],
    // list: [  { validator: this.validateList } ]
  };

  function validateList(rule, value, callback) {
    if (!value || value.length === 0) {
      callback(new Error('报价明细列表不能为空'));
    } else {
      const errors = [];
      value.forEach((quotation, index) => {
        if (!quotation.productName) {
          errors.push(new Error(`第${index + 1}个报价明细的品名不能为空`));
        }
        if (!quotation.sumOfMoney) {
          errors.push(new Error(`第${index + 1}个报价明细的金额不能为空`));
        }
      });
      callback(errors.length ? errors : ''); // 如果错误数组非空，则调用回调函数并传递错误信息；否则传递空字符串表示验证通过。
    }
  }

  const columns = ref([
    {
      title: '品名',
      dataIndex: 'productName',
      ellipsis: true,
      customCell: (record, rowIndex) => {
        return {
          colSpan: record.type === 2 ? 4 : 1,
        };
      },
    },
    {
      title: '规格',
      dataIndex: 'specifications',
      ellipsis: true,
      customCell: (record, rowIndex) => {
        return {
          colSpan: record.type === 2 ? 0 : 1,
        };
      },
    },
    {
      title: '比重',
      dataIndex: 'specificWeight',
      ellipsis: true,
      width: 100,
      customCell: (record, rowIndex) => {
        return {
          colSpan: record.type === 2 ? 0 : 1,
        };
      },
    },
    {
      title: '用量',
      dataIndex: 'usagee',
      ellipsis: true,
      width: 100,
      customCell: (record, rowIndex) => {
        return {
          colSpan: record.type === 2 ? 0 : 1,
        };
      },
    },
    {
      title: '单价',
      dataIndex: 'unitPrice',
      ellipsis: true,
      width: 100,
    },
    {
      title: '金额',
      dataIndex: 'sumOfMoney',
      ellipsis: true,
      width: 100,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
    }
  ]);

  function handleInputChange(value, index) {
    let record = form.value.list[index]
    if (record.type === 1 && record.specificWeight != null && record.usagee != null && record.unitPrice != null) {
      let sum = record.specificWeight * record.usagee * record.unitPrice
      form.value.list[index].sumOfMoney = sum
    } else if (record.type === 3 && record.usagee != null && record.unitPrice != null) {
      form.value.list[index].sumOfMoney = record.usagee * record.unitPrice
    }
    calculateMoney(value, index)
  }

  const map = new Map([
    [0, "元/米"],
    [3, "元/平方米"],
    [1, "元/个"],
    [2, "元/套"],
  ])

  function handlePricingChange(e) {
    let type = form.value.pricingType
    if (type) {
      let unit = map.get(type)
      if (form.value.list[form.value.list.length - 1] !== unit) {
        for (let i = 0; i < form.value.list.length; i++) {
          if (form.value.list[i].type > 4) {
            form.value.list[i].specifications = unit
          }
        }
      }
      calculateMoney(0,0)
    }
  }

  function calculateMoney(value, operateIndex) {
    let sum = 0
    for (let index = 0; index < form.value.list.length; index++) {
      let item = form.value.list[index]
      if (item.type === 1 || item.type === 3
          || item.type === 6 || item.type === 7 || item.type === 8 || item.type === 9 || item.type === 10) {
          sum += item.sumOfMoney
      } else if (item.type === 2) {
        // 损耗
        if (item.unitPrice != null && item.unitPrice > 0 && sum !== 0) {
          form.value.list[index].sumOfMoney = sum * item.unitPrice / 100
          sum += item.sumOfMoney
        }
      } else if (item.type === 4) {
        // 主材合计
        form.value.list[index].sumOfMoney = sum
      } else if (item.type === 5 && sum !== 0)   {
        // 主材单价
        if (form.value.quotationLong !== null && form.value.pricingType !==3 ) {
          form.value.list[index].sumOfMoney = sum / form.value.quotationLong
        } else if (form.value.quotationLong !== null && form.value.quotationHeight !== null && form.value.pricingType ===3 ) {
          form.value.list[index].sumOfMoney = sum / (form.value.quotationLong * form.value.quotationHeight)
        }
        sum = form.value.list[index].sumOfMoney
      } else if (item.type === 11 && item.unitPrice != null && item.unitPrice > 0 && sum !== 0) {
        // 利润
        form.value.list[index].sumOfMoney = sum * item.unitPrice / 100
        sum += item.sumOfMoney
      } else if (item.type === 12){
        // 出厂单价
        form.value.list[index].sumOfMoney = sum
      } else if (item.type === 13 && item.unitPrice != null && item.unitPrice > 0 && sum !== 0){
        // 税金
        form.value.list[index].sumOfMoney = sum *  item.unitPrice / 100
        sum += item.sumOfMoney
      } else if (item.type === 14) {
        form.value.list[index].sumOfMoney = sum
      }
    }
  }

  function getCheckboxProps(record) {
    return {
      disabled: record.type !== 1 && record.type !== 3, // 不是主材或配件无法选中删除
      name: record.type,
    }
  }
  // 添加主材/配件
  function addItem(type) {
    let index
    if (type === 1) {
      index = form.value.list.findIndex(item => item.type === 2)
    } else {
      index = form.value.list.findIndex(item => item.type === 4)
    }
    if (index !== -1) {
      let obj = {
        quotationId: quotationId,
        serialNumber: index+1,
        productName: "",
        specifications: "",
        specificWeight: null,
        usagee: null,
        unitPrice: null,
        sumOfMoney: null,
        remark: "",
        type: type,
        disabledFlag: 0,
      }
      form.value.list.splice(index, 0, obj)
    } else {
      message.error('添加失败,请联系管理员!');
    }
  }

  // 选择表格行
  const selectedRowKeyList = ref([]);

  function onSelectChange(selectedRowKeys) {
    selectedRowKeyList.value = selectedRowKeys;
  }

  function onDelete() {
    selectedRowKeyList.value.sort((a,b) => b-a) // 降序
    for (let i = 0; i < selectedRowKeyList.value.length; i++) {
      let index = selectedRowKeyList.value[i]
      form.value.list.splice(index, 1)
    }
    selectedRowKeyList.value = []
  }

  async function onSubmit() {
    try {
      await formRef.value.validateFields();
      await edit();
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  async function edit() {
    SmartLoading.show();
    try {
      let sumOfMoney = form.value.list[form.value.list.length - 1].sumOfMoney
      form.value.comprehensiveUnitPrice = sumOfMoney != null ? sumOfMoney : 0
      form.value.projectId = projectId
      await quotationApi.edit(form.value);
      message.success('操作成功');
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }

  const calculateRef = ref();
  function showCalculate() {
    calculateRef.value.show()
  }

  let templateId = ref();
  let templateDetail = {};
  let templateList = ref([]);

  async function queryTemplateList() {
    try {
      let resp = await quotationTemplateApi.queryAll();
      templateList.value = resp.data;
    } catch (e) {
      smartSentry.captureError(e);
    }
  }

  function onTemplateChange(value) {
    templateDetail = templateList.value.find(item => item.templateId === value)
    form.value.quotationName = templateDetail.templateName ?? ''
    form.value.quotationLong = templateDetail.templateLong ?? ''
    form.value.quotationHeight = templateDetail.templateHeight ?? ''
    form.value.remark = templateDetail.remark ?? ''
    queryTemplateItems()
  }

  async function queryTemplateItems() {
    try {
      let resp = await quotationTemplateApi.queryItemsById(templateId.value);
      form.value.list = resp.data
    } catch (e) {
      smartSentry.captureError(e);
    }
  }


</script>

<style scoped lang="less">
  .form-item-no-margin{
    margin-bottom: 0;
  }
  .operate-header {
    background-color: #fff;
    padding: 10px;
    //position: fixed;
    //right: 0;
    //top:90px;
    //width: 85%;
    //z-index: 2000;
  }
</style>